<template>
  <div class="h-screen flex flex-col bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm border-b flex items-center px-4 py-3">
      <button @click="openSidebar" class="mr-3">
        <svg class="w-6 h-6 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
        </svg>
      </button>
      <div class="flex items-center flex-1">
        <div class="w-8 h-8 bg-gradient-to-br from-pink-500 to-rose-600 rounded-full flex items-center justify-center">
          <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
          </svg>
        </div>
        <div class="ml-3">
          <h1 class="text-lg font-semibold text-gray-900">AI恋爱大师</h1>
          <p class="text-xs text-green-500">在线</p>
        </div>
      </div>
      <button @click="startNewConversation" class="ml-2">
        <svg class="w-6 h-6 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
        </svg>
      </button>
    </header>

    <!-- 聊天区域 -->
    <main class="flex-1 overflow-hidden">
      <!-- 欢迎界面 -->
      <div v-if="messages.length === 0" class="h-full flex flex-col items-center justify-center p-6 text-center">
        <div class="w-20 h-20 bg-gradient-to-br from-pink-500 to-rose-600 rounded-full flex items-center justify-center mb-4">
          <svg class="w-10 h-10 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
          </svg>
        </div>
        <h2 class="text-xl font-bold text-gray-900 mb-2">AI恋爱大师</h2>
        <p class="text-gray-600 text-sm leading-relaxed max-w-xs">
          我是您的专业恋爱咨询师，可以为您提供情感建议、约会技巧、沟通指导等服务。
        </p>
      </div>

      <!-- 聊天记录 -->
      <div v-else class="h-full overflow-y-auto px-4 py-4" ref="chatContainer">
        <div class="space-y-4">
          <div
            v-for="(message, index) in messages"
            :key="index"
            class="flex"
            :class="message.type === 'user' ? 'justify-end' : 'justify-start'"
          >
            <!-- AI消息 -->
            <div v-if="message.type === 'ai'" class="flex items-start max-w-[85%]">
              <div class="w-8 h-8 bg-gradient-to-br from-pink-500 to-rose-600 rounded-full flex items-center justify-center mr-2 flex-shrink-0">
                <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                </svg>
              </div>
              <div class="bg-white rounded-2xl px-4 py-3 shadow-sm border border-gray-100">
                <div v-if="message.loading" class="flex space-x-1">
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-pulse"></div>
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-pulse" style="animation-delay: 0.2s"></div>
                  <div class="w-2 h-2 bg-gray-400 rounded-full animate-pulse" style="animation-delay: 0.4s"></div>
                </div>
                <MarkdownRenderer v-else :content="message.content" class="text-gray-800 text-sm leading-relaxed" />
              </div>
            </div>

            <!-- 用户消息 -->
            <div v-else class="flex items-start max-w-[85%] justify-end">
              <div class="bg-gradient-to-r from-pink-500 to-rose-600 text-white rounded-2xl px-4 py-3 mr-2">
                <div class="text-sm leading-relaxed whitespace-pre-wrap">{{ message.content }}</div>
              </div>
              <div class="w-8 h-8 bg-gray-400 rounded-full flex items-center justify-center flex-shrink-0">
                <span class="text-white text-xs font-medium">{{ userInitial }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 底部输入区域 -->
    <footer class="bg-white border-t px-4 py-3">
      <div class="flex items-end space-x-3">
        <div class="flex-1">
          <textarea
            v-model="inputMessage"
            @keydown="handleKeyDown"
            placeholder="请输入您的恋爱问题..."
            class="w-full p-3 border border-gray-300 rounded-2xl resize-none focus:outline-none focus:ring-2 focus:ring-pink-500 focus:border-transparent text-sm"
            rows="1"
            style="min-height: 44px; max-height: 120px;"
            :disabled="isLoading"
          ></textarea>
        </div>
        <button
          @click="toggleNetworkSearch"
          :class="[
            'p-3 rounded-full border transition-colors flex items-center',
            networkSearch 
              ? 'bg-blue-500 text-white border-blue-500' 
              : 'bg-white text-gray-600 border-gray-300'
          ]"
          :disabled="isLoading"
        >
          <svg class="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <span class="text-xs">联网搜索</span>
        </button>
        <button
          @click="isLoading ? handleAbort() : sendMessage()"
          :disabled="!isLoading && !inputMessage.trim()"
          :class="[
            'p-3 rounded-full transition-colors',
            isLoading 
              ? 'bg-red-500 text-white' 
              : inputMessage.trim() 
                ? 'bg-gradient-to-r from-pink-500 to-rose-600 text-white'
                : 'bg-gray-300 text-gray-500'
          ]"
        >
          <svg v-if="isLoading" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
          <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
          </svg>
        </button>
      </div>
    </footer>

    <!-- 历史会话侧边栏抽屉 -->
    <transition name="fade">
      <div v-if="showSidebar" class="fixed inset-0 z-50 bg-black bg-opacity-30" @click.self="showSidebar = false">
        <div class="absolute left-0 top-0 bottom-0 w-4/5 max-w-xs bg-white flex flex-col">
          <!-- 历史会话分组列表 -->
          <div class="flex-1 overflow-y-auto">
            <template v-for="(group, groupKey) in groupedChats" :key="groupKey">
              <div class="px-4 py-2 text-xs text-gray-400">{{ groupKey }}</div>
              <div v-for="item in group" :key="item.chatId"
                :class="['px-4 py-3 border-b cursor-pointer', selectedChatId === item.chatId ? 'bg-gray-100 font-bold' : '']"
                @click="selectHistory(item)"
              >
                <div class="truncate">{{ item.title }}</div>
                <div class="text-xs text-gray-400 mt-1">{{ formatTimeHM(item.createtime) }}</div>
              </div>
            </template>
            <div v-if="chatStore.loadingList" class="p-4 text-center text-gray-400">加载中...</div>
            <div v-if="!chatStore.loadingList && chatStore.chatList.length === 0" class="p-4 text-center text-gray-400">暂无会话</div>
          </div>
          <!-- 底部用户名和注销 -->
          <div class="p-4 border-t flex items-center justify-between">
            <span class="text-gray-500 text-sm truncate">{{ authStore.username }}</span>
            <button class="text-pink-500 text-sm" @click="logout">注销</button>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { useChatStore } from '../stores/chat'
import { createSSEConnection, createChat } from '../api/index'
import MarkdownRenderer from '../components/MarkdownRenderer.vue'

const router = useRouter()
const authStore = useAuthStore()
const chatStore = useChatStore()

// 响应式数据
const messages = ref([])
const inputMessage = ref('')
const isLoading = ref(false)
const networkSearch = ref(false)
const showUserMenu = ref(false)
const chatContainer = ref(null)
const abortController = ref(null)
const chatId = ref('')
const uid = ref(null)
// 新增：SSE数据累积缓冲区
let currentSSEBuffer = ''
const showSidebar = ref(false)
const selectedChatId = ref('')

// 计算属性
const userInitial = computed(() => {
  return authStore.username ? authStore.username.charAt(0).toUpperCase() : 'U'
})

// 时间分组逻辑（复用桌面端）
function groupChatsByDate(list) {
  const groups = { '今天': [], '昨天': [], '一周内': [], '更早': [] }
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  list.forEach(item => {
    const date = new Date(item.createtime)
    const thatDay = new Date(date.getFullYear(), date.getMonth(), date.getDate())
    const diff = (today - thatDay) / (1000 * 60 * 60 * 24)
    if (diff === 0) groups['今天'].push(item)
    else if (diff === 1) groups['昨天'].push(item)
    else if (diff > 1 && diff <= 7) groups['一周内'].push(item)
    else groups['更早'].push(item)
  })
  return Object.fromEntries(Object.entries(groups).filter(([k, v]) => v.length > 0))
}
const groupedChats = computed(() => groupChatsByDate(chatStore.chatList))

function formatTimeHM(dateStr) {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false })
}

// 初始化聊天
const initChat = async () => {
  try {
    console.log('🔄 开始创建聊天会话...')
    const response = await createChat()
    console.log('🎯 CREATE响应:', response)
    if (!response) {
      throw new Error('create接口无响应')
    }
    if (response.chatId && response.id) {
      chatId.value = response.chatId
      uid.value = response.id
      authStore.uid = response.id // 自动同步到全局
      console.log('✅ 设置成功 - chatId:', chatId.value, 'uid:', uid.value)
    } else if (response.id) {
      chatId.value = response.id
      uid.value = response.id
      authStore.uid = response.id // 自动同步到全局
      console.log('⚠️ 只有id字段 - chatId:', chatId.value, 'uid:', uid.value)
    } else {
      throw new Error('响应中缺少必要字段（chatId或id）')
    }
  } catch (error) {
    console.error('❌ 创建聊天失败:', error)
    if (error.message?.includes('403') || error.response?.status === 403) {
      router.push('/login')
      return
    }
    chatId.value = 'test-chat-id'
    uid.value = 'test-uid'
    authStore.uid = 'test-uid' // 自动同步到全局
    console.log('🔧 使用测试值 - chatId:', chatId.value, 'uid:', uid.value)
  }
}

// 方法
const goBack = () => {
  router.push('/mobile-home')
}

const startNewConversation = async () => {
  if (isLoading.value) return
  
  // 如果有对话历史，询问确认
  if (messages.value.length > 0) {
    if (confirm('确定要开始新对话吗？当前对话记录将被清除。')) {
      // 清空当前对话
      messages.value = []
      inputMessage.value = ''
      isLoading.value = false
      chatId.value = ''
      uid.value = null
      
      console.log('🔄 开启新对话，重新获取chatId和uid...')
      
      // 重新初始化聊天，获取新的chatId和uid
      await initChat()
      
      console.log('新对话已开始')
    }
  } else {
    // 没有对话历史，直接清空并重新初始化
    messages.value = []
    inputMessage.value = ''
    chatId.value = ''
    uid.value = null
    await initChat()
  }
}

const toggleNetworkSearch = () => {
  if (isLoading.value) return
  networkSearch.value = !networkSearch.value
}

const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
  })
}

const handleKeyDown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    if (!isLoading.value && inputMessage.value.trim()) {
      sendMessage()
    }
  }
}

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return
  if (!chatId.value) {
    console.error('❌ 没有chatId，无法发送消息')
    return
  }
  if (!uid.value) {
    console.error('❌ 没有uid，无法发送消息')
    return
  }
  const userMessage = inputMessage.value.trim()
  inputMessage.value = ''
  messages.value.push({
    type: 'user',
    content: userMessage,
    timestamp: Date.now()
  })
  const backendMessage = networkSearch.value ? `使用联网搜索工具进行查询：${userMessage}` : userMessage
  const aiMessageIndex = messages.value.length
  messages.value.push({
    type: 'ai',
    content: '',
    loading: true,
    timestamp: Date.now()
  })
  currentSSEBuffer = ''
  scrollToBottom()
  isLoading.value = true
  try {
    const controller = createSSEConnection(
      '/ai/love_app/chat/sse/emitter',
      { 
        message: backendMessage, 
        chatId: chatId.value, 
        uid: uid.value, 
        networkSearch: networkSearch.value 
      },
      (data) => {
        // 优化：去除多余换行，兼容后端分片
        if (messages.value[aiMessageIndex] && messages.value[aiMessageIndex].loading) {
          messages.value[aiMessageIndex].loading = false
        }
        if (data !== undefined && data !== null) {
          currentSSEBuffer += data.replace(/\r\n|\r|\n/g, '\n')
        }
        if (messages.value[aiMessageIndex]) {
          messages.value[aiMessageIndex].content = currentSSEBuffer.replace(/\n{3,}/g, '\n\n')
          scrollToBottom()
        }
      },
      (error) => {
        isLoading.value = false
        if (messages.value[aiMessageIndex]) {
          messages.value[aiMessageIndex].loading = false
          if (error?.limit) {
            messages.value[aiMessageIndex].content = error.message
          } else {
            messages.value[aiMessageIndex].content += '\n[连接中断]'
          }
        }
        scrollToBottom()
      },
      () => {
        isLoading.value = false
        if (messages.value[aiMessageIndex]) {
          messages.value[aiMessageIndex].loading = false
          messages.value[aiMessageIndex].content = currentSSEBuffer.trim()
        }
        currentSSEBuffer = ''
        scrollToBottom()
      }
    )
    abortController.value = controller
  } catch (error) {
    if (messages.value[aiMessageIndex]) {
      messages.value[aiMessageIndex] = {
        type: 'ai',
        content: `抱歉，发送消息时出现错误：${error.message || '未知错误'}。请稍后重试。`,
        loading: false,
        timestamp: Date.now()
      }
    }
    isLoading.value = false
    scrollToBottom()
  }
}

const handleAbort = () => {
  if (abortController.value && typeof abortController.value.abort === 'function') {
    abortController.value.abort()
  }
  isLoading.value = false
  // 找到最后一个AI消息，结束loading并加提示
  const lastAiMsg = [...messages.value].reverse().find(m => m.type === 'ai' && m.loading)
  if (lastAiMsg) {
    lastAiMsg.loading = false
    if (!lastAiMsg.content || !lastAiMsg.content.trim()) {
      lastAiMsg.content = '[回复已终止]'
    } else {
      lastAiMsg.content += '\n[回复已终止]'
    }
  }
}

const openSidebar = () => {
  showSidebar.value = true
  chatStore.loadChatList(authStore.uid) // 必须用最新的uid
}

const selectHistory = async (item) => {
  selectedChatId.value = item.chatId
  await chatStore.loadChatDetail(authStore.uid, item.chatId)
  messages.value = (chatStore.currentMessages || []).map(msg => ({
    type: msg.messageType === 'USER' ? 'user' : 'ai',
    content: msg.text,
    timestamp: msg.createTime
  }))
  showSidebar.value = false
}

const logout = () => {
  authStore.logout()
  router.push('/login')
}

onMounted(() => {
  initChat()
  scrollToBottom()
})

onUnmounted(() => {
  isLoading.value = false
})
</script>

<!-- 聊天气泡样式优化 -->
<style scoped>
.bg-white.rounded-2xl {
  max-width: 80vw;
  word-break: break-all;
  white-space: pre-line;
}
.bg-gradient-to-r.from-pink-500.to-rose-600.text-white.rounded-2xl {
  max-width: 80vw;
  word-break: break-all;
  white-space: pre-line;
}
</style> 